import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';

class SoftInputPage extends StatelessWidget {
  const SoftInputPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('聊天框'),
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemBuilder: _buildChatItem,
            ),
          ),
          const ChatWidget(),
        ],
      ),
      // resizeToAvoidBottomInset: true,
    );
  }

  Widget? _buildChatItem(BuildContext context, int index) {
    if (index % 3 == 0) {
      return const ListTile(
        title: Text('我是一条消息'),
        leading: CircleAvatar(
          child: Text('我'),
        ),
        tileColor: Colors.grey,
      );
    } else {
      return const ListTile(
        title: Text('我是一条消息'),
        trailing: CircleAvatar(
          child: Text('你'),
        ),
      );
    }
  }
}

class ChatWidget extends StatefulWidget {
  const ChatWidget({super.key});

  @override
  State<ChatWidget> createState() => _ChatWidgetState();
}

class _ChatWidgetState extends State<ChatWidget> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addObserver(this);
  }

  var height = 0.0;

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    // final softKeyboardHeight = MediaQuery.of(context).viewInsets;
    // print('softKeyboardHeight: $softKeyboardHeight');
    // setState(() {});

    for (final view in WidgetsBinding.instance.platformDispatcher.views) {
      print('view: viewInsets bottom: ${view.viewInsets.bottom}');
      height = view.viewInsets.bottom;
    }

    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    // final softKeyboardHeight = MediaQuery.of(context).viewInsets;
    // print('softKeyboardHeight: $softKeyboardHeight');
    return HookConsumer(
      builder: (context, ref, child) {
        return SizedBox(
          child: CupertinoTextField(
            placeholder: '底部高度: $height',
            onSubmitted: (value) {
              print('onSubmitted: $value');
            },
          ),
        );
      },
    );
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }
}
